package com.zhuxulin.midi.event.meta;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.zhuxulin.midi.event.MidiEvent;
import com.zhuxulin.midi.util.MidiUtil;
import com.zhuxulin.midi.util.ReadVarLen;
/**
 * FF 00 event
 * @author ZhuXulin
 *
 */
public class SequenceNumber extends MetaEvent {

	private int mNumber;
	
	public SequenceNumber(long tick, long delta, int number) {
		super(tick, delta, MetaEvent.SEQUENCE_NUMBER, new ReadVarLen(2));
		
		mNumber = number;
	}
	
	public int getMostSignificantBits() {
		return mNumber >> 8;
	}
	public int getLeastSignificantBits() {
		return mNumber & 0xFF;
	}
	public int getSequenceNumber() {
		return mNumber;
	}
	
	@Override
	public void writeToFile(OutputStream out) throws IOException {
		super.writeToFile(out);
		
		out.write(2);
		out.write(getMostSignificantBits());
		out.write(getLeastSignificantBits());
	}

	public static SequenceNumber parseSequenceNumber(long tick, long delta, InputStream in) throws IOException {
		
		in.read();		// Size = 2;
		int msb = in.read();
		int lsb = in.read();
		int number = (msb << 8) + lsb;
		
		return new SequenceNumber(tick, delta, number);
	}

	@Override
	protected int getEventSize() {
		return 6;
	}

	@Override
	public int compareTo(MidiEvent other) {
		
		if(mTick != other.getTick()) {
			return mTick < other.getTick() ? -1 : 1;
		}
		if(mDelta.getValue() != other.getDelta()) {
			return mDelta.getValue() < other.getDelta() ? 1 : -1;
		}
		
		if(!(other instanceof SequenceNumber)) {
			return 1;
		}
		
		SequenceNumber o = (SequenceNumber)other;

		if(mNumber != o.mNumber) {
			return mNumber < o.mNumber ? -1 : 1;
		}
		return 0;
	}
	@Override
	public byte[] getCmd() {
		cmd = new byte[6];
		MidiUtil.addByte(new byte[] { (byte) 0xff, 0x51, 0x02 },
				new byte[]{(byte) getMostSignificantBits(),(byte) getLeastSignificantBits()});
		return cmd;
	}
}
